package com.kyang.musiconline.service;

import com.kyang.musiconline.dao.UserDao;
import com.kyang.musiconline.model.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * @author kyang
 */
@Slf4j
@Service
public class UserService {
    @Autowired
    private UserDao userDao;

    public boolean register(User user) {
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        log.info("user register");
        return userDao.insert(user);
    }

    public User login(String account, String password) {
        try {
            User loginUser = userDao.getUserByAccount(account);
            String pwd = DigestUtils.md5DigestAsHex(password.getBytes());
            if (pwd.equals(loginUser.getPassword())) {
                log.info("{} Login successful", loginUser.getAccount());
                return loginUser;
            }
            return null;
        } catch (EmptyResultDataAccessException e) {
            log.error("Login User not exists: {}", e.getMessage());
            return null;
        }
    }

    public boolean editItem(User user) {
        log.info("User edit successful: {}", user.getAccount());
        return userDao.changeUserInfo(user);
    }

    public boolean changePwd(String userId, String password) {
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        return userDao.changePassword(userId, password);
    }

    public User getInfoById(String userId) {
        try {
            log.info("Get User info: {}", userId);
            return userDao.getUserById(userId);
        } catch (EmptyResultDataAccessException e) {
            log.error("User not exists: {}", e.getMessage());
            return null;
        }
    }
}
